import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams } from 'react-router-dom';
import CourseRecordListABI from "../contract/ABIs/CourseList.json"; // 课程列表合约 ABI
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI
import * as XLSX from 'xlsx'; // 导入 XLSX 库用于解析 Excel 文件
import { Upload, message, Button, List } from 'antd'; // 导入 Ant Design 的 Upload 和 Button 组件
import { InboxOutlined, DownloadOutlined } from '@ant-design/icons'; // 导入 Ant Design 的图标

import CourseRecordListAddress from "../contract/ADDRESSes/CourseListAddress.js"; // 课程列表合约地址
import AdminNavBar from './nav/AdminNavBar.js'
import Head from './nav/Head.js';


const Admin_addMultiCourses = () => {
    const [web3, setWeb3] = useState(null);
    const { address } = useParams();
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);

    const [surriculumSystems, setSurriculumSystems] = useState('');//课程体系
    const [newCourseNumber, setnewCourseNumber] = useState('');//课程编号用来选择更新课程
    const [newCourseName, setnewCourseName] = useState('');//课程名称
    const [newCourseNature, setnewCourseNature] = useState('');//课程性质
    const [newCourseAttribute, setnewCourseAttribute] = useState('');//课程属性
    const [newCredit, setnewCredit] = useState(0);//学分
    const [newContactHour, setnewContactHour] = useState(0);//学时
    const [newSemesterOffered, setnewSemesterOffered] = useState(0);//开设学期
    const [newGradeScale, setnewGradeScale] = useState(0);//考试成绩占比

    const [deleteModalOpen, setDeleteModalOpen] = useState(false);

    const [MultiCourses, setMultiCourses] = useState([]); // 课程信息结构体数组
    const [fileList, setFileList] = useState([]); // 保存上传文件列表

    useEffect(() => {
        async function init() {
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    const courseRecordListInstance = new web3Instance.eth.Contract(
                        CourseRecordListABI,
                        CourseRecordListAddress
                    );
                    setcontractCourseRecordList(courseRecordListInstance);

                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    setIsAdmin(currentAddress === ownerAddress);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    // 模态框显示
    const openAddCourseModal = () => {
        setSurriculumSystems('');
        setnewCourseNumber('');
        setnewCourseName('');
        setnewCourseNature('');
        setnewCourseAttribute('');
        setnewCredit(0);
        setnewContactHour(0);
        setnewSemesterOffered(0);
        setnewGradeScale(0);
        setDeleteModalOpen(true);
    };

    // 解析文件
    const handleFileUpload = ({ file }) => {
        const reader = new FileReader();
        reader.onload = (evt) => {
            const data = evt.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[sheetName];
            const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
            const header = jsonData[0];

            const templateHeader = [
                'surriculumSystems',
                'courseNumbers',
                'courseName',
                'courseNatures',
                'courseAttributes',
                'credits',
                'contactHours',
                'semestersOffered',
                'gradeScales'
            ];

            const isValid = header.every((column, index) => column === templateHeader[index]);
            if (!isValid) {
                message.error('上传的文件格式不正确，请使用模板文件');
                return;
            }

            const newMultiCourses = jsonData.slice(1).map(row => ({
                surriculumSystem: row[0],
                courseNumber: row[1].toString(),
                courseName: row[2],
                courseNature: row[3],
                courseAttribute: row[4].toString(),
                credit: row[5],
                contactHour: row[6],
                semesterOffered: row[7],
                gradeScale: row[8],
            }));
            setMultiCourses(newMultiCourses);
            setFileList([...fileList, file]);
            message.success(`${file.name} 文件上传成功`);
        };
        reader.readAsBinaryString(file);
    };

    // 批量添加课程
    const AddStudents = async () => {
        if (contractCourseRecordList) {
            try {
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log('MultiCourses', MultiCourses)
                await contractCourseRecordList.methods.addMultiCourse(MultiCourses).send({ from: fromAddress, gas: 5000000 });
                alert("添加成功");
            } catch (error) {
                console.error(error);
                alert("添加失败");
            }
        }
    };

    // 添加单个课程
    const addSingleCourse = async () => {
        if (contractCourseRecordList) {
            try {
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                const newCourse = {
                    surriculumSystem: surriculumSystems,
                    courseNumber: newCourseNumber,
                    courseName: newCourseName,
                    courseNature: newCourseNature,
                    courseAttribute: newCourseAttribute,
                    credit: newCredit,
                    contactHour: newContactHour,
                    semesterOffered: newSemesterOffered,
                    gradeScale: newGradeScale,
                };
                const updatedMultiCourses = [...MultiCourses, newCourse];
                setMultiCourses(updatedMultiCourses);
                await contractCourseRecordList.methods.addMultiCourse(updatedMultiCourses).send({ from: fromAddress });
                alert("添加成功");
            } catch (error) {
                console.error(error);
                alert("添加失败");
            }
        }
    };

    // 删除上传的文件
    const handleRemove = (file) => {
        setFileList(fileList.filter(item => item.uid !== file.uid));
    };

    // 下载模板文件
    const downloadTemplate = () => {
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet([[
            'surriculumSystems', 'courseNumbers', 'courseName', 'courseNatures', 'courseAttributes', 'credits', 'contactHours', 'semestersOffered', 'gradeScales'
        ]]);
        XLSX.utils.book_append_sheet(wb, ws, "Template");
        XLSX.writeFile(wb, "课程模板.xlsx");
    };

    return (
        <div>
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {isAdmin && (
                <div className="page-wrapper">
                    <div className="main-container" style={{
                        backgroundColor: '#FFFFFF'
                    }}>
                        <AdminNavBar address={address}></AdminNavBar>

                        <div className="app-container">
                            <Head></Head>

                            <div className="app-body">
                                <div className="container-fluid">

                                    <div>
                                        <main className="page hire-me-page">
                                            <section className="portfolio-block hire-me">

                                                <div className="container">
                                                    <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                        data-bs-theme="light"
                                                        style={{
                                                            backgroundColor: 'rgba(36, 36, 36, 0.6)'
                                                        }}
                                                    >

                                                        <h1>批量添加课程</h1>
                                                        <div className="mb-3">

                                                            <div className="mt-3">
                                                                <Button
                                                                    type="primary"
                                                                    icon={<DownloadOutlined />}
                                                                    size="large"
                                                                    onClick={downloadTemplate}
                                                                >
                                                                    下载模板文件
                                                                </Button>
                                                            </div>

                                                            {/* 使用 Ant Design 的 Upload 组件 */}
                                                            <Upload.Dragger
                                                                name="file"
                                                                multiple={true}
                                                                accept=".xlsx, .xls"
                                                                beforeUpload={() => false}
                                                                onChange={handleFileUpload}
                                                                showUploadList={false}
                                                            >
                                                                <p className="ant-upload-drag-icon">
                                                                    <InboxOutlined />
                                                                </p>
                                                                <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                                                                <p className="ant-upload-hint">支持扩展名：.xlsx, .xls</p>
                                                            </Upload.Dragger>

                                                            {/* 显示已上传的文件列表 */}
                                                            <List
                                                                size="small"
                                                                header={<div>已上传文件列表</div>}
                                                                bordered
                                                                dataSource={fileList}
                                                                renderItem={file => (
                                                                    <List.Item
                                                                        actions={[<Button onClick={() => handleRemove(file)}>删除</Button>]}
                                                                    >
                                                                        {file.name}
                                                                    </List.Item>
                                                                )}
                                                            />

                                                            <div className="mb-3 mt-4">
                                                                <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={AddStudents}>确认批量添加课程</button>
                                                            </div>

                                                            {deleteModalOpen && (
                                                                <div className="delete-modal">
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">课程体系</label>
                                                                        <input className="form-control item" type="text" placeholder="课程体系" value={surriculumSystems} onChange={(e) => setSurriculumSystems(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">课程编号</label>
                                                                        <input className="form-control item" type="text" placeholder="课程编号" value={newCourseNumber} onChange={(e) => setnewCourseNumber(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">课程名称</label>
                                                                        <input className="form-control item" type="text" placeholder="课程名称" value={newCourseName} onChange={(e) => setnewCourseName(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">课程性质</label>
                                                                        <input className="form-control item" type="text" placeholder="课程性质" value={newCourseNature} onChange={(e) => setnewCourseNature(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">课程属性</label>
                                                                        <input className="form-control item" type="text" placeholder="课程属性" value={newCourseAttribute} onChange={(e) => setnewCourseAttribute(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">学分</label>
                                                                        <input className="form-control item" type="number" placeholder="学分" value={newCredit} onChange={(e) => setnewCredit(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">学时</label>
                                                                        <input className="form-control item" type="number" placeholder="学时" value={newContactHour} onChange={(e) => setnewContactHour(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">开设学期</label>
                                                                        <input className="form-control item" type="number" placeholder="开设学期" value={newSemesterOffered} onChange={(e) => setnewSemesterOffered(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3">
                                                                        <label className="form-label" htmlFor="name">考试成绩占比</label>
                                                                        <input className="form-control item" type="number" placeholder="考试成绩占比" value={newGradeScale} onChange={(e) => setnewGradeScale(e.target.value)} />
                                                                    </div>
                                                                    <div className="mb-3 mt-4">
                                                                        <button className="btn btn-primary btn-lg d-block w-100" type="button" onClick={addSingleCourse}>添加</button>
                                                                    </div>
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                </div>

                                            </section>
                                        </main>
                                    </div>


                                </div>
                            </div>
                            <div className="app-footer">
                                <span>
                                    © Bootstrap Gallery 2023
                                </span>
                            </div>
                        </div>
                    </div>

                </div>
            )}
        </div>
    );
};

export default Admin_addMultiCourses;
